import React, { useState, useEffect } from 'react';
import { useTimer, sleep, uPlc, loc_dt, obj_str } from 'sui';

const PreView = ({ children }) => {
    return (
        <div className="text-white text-3xl flex items-center justify-center h-full">
            {children}
        </div>
    );
};

const BaseClient = ({ wsn, line, children }) => {
    const action = (state, action) => {
        if (!wsn || !line) {
            return state;
        }

        const val = {};
        val[wsn] = loc_dt(new Date());

        const cmd = {
            line: line,
            sn: "heart_wsn",
            v: val,
        };

        uPlc(null, "put", cmd);

        return state;
    }

    useTimer(action, 1000);

    return <div>{children}</div>;
};

const Base = ({ wsn, line, children }) => {
    const [fin, setFin] = useState("check");

    useEffect(() => {
        if (!wsn || !line) {
            return;
        }

        const cmd = {
            line: line,
            sn: "heart_wsn",
        };

        uPlc(null, "get", cmd, r => {
            const s = obj_str(r, wsn);

            sleep(1000 * 3, () => {
                uPlc(null, "get", cmd,
                    r => {
                        const e = obj_str(r, wsn);

                        if (e > s) {
                            setFin("ng");
                        } else {
                            setFin("job")
                        }
                    }, e => setFin("job"));
            });
        }, e => setFin("job"));
    }, [wsn, line]);

    if (fin === "job") {
        return <BaseClient wsn={wsn} line={line}>{children}</BaseClient>;
    }

    if (fin === "ng") {
        return <PreView>此工位已经运行，禁止重复进入</PreView>;
    }

    return <PreView>检测工位状态</PreView>;
};

export {Base};
